using CatLib;
using CatLib.Container;
using CatLib.EventDispatcher;
using Cysharp.Threading.Tasks;
using GameFramework.Event;
using GameFramework.Fsm;
using GameFramework.Procedure.Attribute;
using GameFramework.Procedure.Fsm;
using GameFramework.Reference;

namespace GameLogic.Launch
{
    /// <summary>
    /// 检查版本流程
    /// </summary>
    [Procedure]
    public sealed class CheckVersionProcedure : AFsmProcedure
    {
        private bool m_CheckVersionComplete;
        private bool m_NeedToUpgradeApp;
        private bool m_NeedToUpgradeResources;
        
        public override void OnEnter(IFsm fsm)
        {
            base.OnEnter(fsm);
            m_CheckVersionComplete = false;
            m_NeedToUpgradeApp = false;
            m_NeedToUpgradeResources = false;
            
            EventService.That.Raise(this, LaunchStepUpdatedEvent.Acquire(LaunchStep.CheckVersion));
            CheckVersionAsync().Forget();
        }

        public override void OnUpdate(IFsm fsm, float elapseSeconds, float realElapseSeconds)
        {
            base.OnUpdate(fsm, elapseSeconds, realElapseSeconds);

            if (!m_CheckVersionComplete)
                return;

            if (m_NeedToUpgradeApp)
            {
                // 需要更新App
                return;
            }

            if (m_NeedToUpgradeResources)
            {
                // 需要更新资源
                Change<UpdateResourceProcedure>(fsm);
                return;
            }
            
            // 进入下个流程
            Change<LoadConfigProcedure>(fsm);
        }

        /// <summary>
        /// 检查版本号
        /// </summary>
        private async UniTask CheckVersionAsync()
        {
            // TODO 直接当作检查成功
            m_CheckVersionComplete = true;
            m_NeedToUpgradeApp = false;
            m_NeedToUpgradeResources = false;
            
            EventService.That.Raise(this, LaunchStepUpdatedEvent.Acquire(LaunchStep.CheckVersion, 1f));
        }
    }
}